package com.lagou.edu.ctrl;/**
 * @author wangshuai, <shuai.wang@leyantech.com>
 * @date 2020-05-03.
 */

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.feign.EmailServiceFeignClient;
import com.lagou.edu.pojo.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;


@RestController
@RequestMapping("/api/code")
@Validated
public class CodeCtrl {

  @Autowired
  EmailServiceFeignClient emailServiceFeignClient;

  @Autowired
  AuthCodeDao authCodeDao;


  @GetMapping("/create/{email}")
  public boolean create(@PathVariable String email) {

    if (StringUtils.isEmpty(email)) {
      return false;
    }

    int num = ThreadLocalRandom.current().nextInt(100000, 999999);
    //send email
    boolean rst = emailServiceFeignClient.send(email, num + "");
    if (rst) {

      //clear old
      authCodeDao.delete(new AuthCode().setEmail(email));
      //save code
      authCodeDao.save(new AuthCode().setCode(num + "").setEmail(email).setCreateTime(new Date())
      .setExpireTime(new Date(System.currentTimeMillis()+10*60*1000)));



    }

    return rst;
  }


  @PostMapping("/validate/{email}/{code}")
  public boolean validate(@PathVariable String email, @PathVariable String code) {

    if (StringUtils.isEmpty(email)) {
      return false;
    }
    if (StringUtils.isEmpty(code)) {
      return false;
    }

    // check code
    return authCodeDao.count(Example.of(new AuthCode().setEmail(email).setCode(code))) > 0;
  }


}
